<?php
include_once 'app/until/GetData.php';

class MediaCenter extends GetData {

	private $daten;
	public $error = array ();
	private $mediafiles;
	private $paths;
	public $filetyps = array ('text/x-c','image/jpeg', 'image/png', 'image/png', 'image/gif', 'text/plain', 'text/html','application/x-rar','application/zip');
	public $filends = array ('.html','.css', '.jpg', '.png', '.js', '.swf', '.gif','.txt','.jpeg');
	public $inCl = array ('Content'=>'{$content}');
	private $MediaFiles;
	private $FileCountSize;
	private $FileSize;
	private $FileCountSizeLimit = 10;
	private $FileSizeLimit = 5242880;
	public $User_Id;
	public $design;

	public function __construct($match) {
		$this->daten = $match;

		if (empty ( $_SESSION ['UserId'] )) {
			HTTP::redirect ( BASE_URL . '/NotLogin' );
		} else {
			$this->User_Id = $_SESSION ['UserId'];
		}

		$this->paths = array ('media/user/' . $this->User_Id . '/', 'media/user/' . $this->User_Id . '/image/', 'media/user/' . $this->User_Id . '/css/', 'media/user/' . $this->User_Id . '/flash/' );

		$this->FileSize = $this->CountSizeFiles ();
		$this->FileCountSize = $this->CountFiles ();
	}

	public function getWort(RainTPL $design) {
		$this->obj = $design;
		
		$navi = new Db_user_page_static();
		$DBMail = new Db_Mail();
		$navi = $navi->getNavi("Pages","Deine Seiten");		
		$this->design->assign ('navi',$navi);
		
		$this->UserMediaUrl = ConfigFile::Get('BASE_DIR').'/user/'.$this->User_Id.'/mf/';
		$this->UserWebUrl = ConfigFile::Get('BASE_DIR').'/user/'.$this->GetUserById($this->User_Id);
		$this->inCl = array (
	    					'Content'=>'{$content}',
	    					'MediaUrl'=>$this->UserMediaUrl,
                            'WebUrl'=>$this->UserWebUrl
		);

						if ($this->User_Id) {
							$this->design->assign ( 'UnReadedMails', $DBMail->GetCountUnReadedMails ( $this->User_Id ) );
						}

						if ($this->design->get->place && $this->design->get->del) {
							switch (strtoupper ( $this->design->get->place)) {
								case 'MAIN' :
									$unlink = $this->DelFile ( $this->paths [0] . $this->design->get->del);
									Break;
								case 'IMAGE' :
									$unlink = $this->DelFile ( $this->paths [1] . $this->design->get->del);
									break;
								case 'CSS' :
									$unlink = $this->DelFile ( $this->paths [2] . $this->design->get->del);
									break;
								case 'FLASH' :
									$unlink = $this->DelFile ( $this->paths [3] . $this->design->get->del);
									break;
							}
							if ($unlink)
							HTTP::redirect ( BASE_URL . '/mediacenter?success='.$this->design->get->del);
							else
							HTTP::redirect ( BASE_URL . '/mediacenter?error='.$this->design->get->del);
						}
						if ($this->design->File->mediafile) {
						    
							$file = $this->design->File->mediafile;

							if ($this->UploadFile( $file )){
								HTTP::redirect ( BASE_URL . '/mediacenter?success='.$this->error[0]);
							}else{
								HTTP::redirect ( BASE_URL . '/mediacenter?error='.$this->error[0]);
							}
						}
						$this->MediaFiles = $this->GetMediaContent ();

						$this->design->assign ( 'Files', $this->MediaFiles );
						$this->design->assign ( 'FileSize', $this->formatBytes($this->CountSizeFiles()));
						$this->design->assign ( 'FileCount', $this->CountFiles() );

						$this->design->assign ( 'FileSizeLimit', $this->formatBytes($this->FileSizeLimit));
						$this->design->assign ( 'FileCountLimit', $this->FileCountSizeLimit );
						$this->design->assign ( 'FileTyps', $this->filetyps );
						
                    	if( $cache = $this->design->cache( $this->design->ln . '/User/Page/mediacenter', $expire_time = 600 ) )
                		{
                		 	echo $cache;
                		}
                		else
                		{
                		 	$this->design->draw( $this->design->ln . '/User/Page/mediacenter' );
                		}
	}

	protected function GetMediaContent() {
		$final = array ();
		foreach ( $this->paths as $path ) {
			$files = array ();
			$h = opendir ( $path );
			while ( false !== ($o = readdir ( $h )) ) {
				if (! is_file ( $path . $o ))
				continue;
				array_push ( $files,$o );
			}
			array_push ( $final, $files );
		}
		krsort ($final);

		return $final;
	}

	protected function CountFiles() {
		$files = array ();

		foreach ( $this->paths as $path ) {
			$h = opendir ( $path );
			while ( false !== ($o = readdir ( $h )) ) {
				if (! is_file ( $path . $o ))
				continue;
				foreach ( $this->filends as $typs ) {
					if (preg_match ('/'.$typs.'/', $o )) {
						array_push ( $files, $o );
					}
				}
			}
		}
		return count ( $files );
	}
	protected function CountSizeFiles() {
		$sum = 0;
		foreach ( $this->paths as $path ) {
			$handle = opendir ( $path );
			while ( false !== ($file = readdir ( $handle )) ) {
				foreach ( $this->filends as $typs ) {
					if (preg_match ( '/'.$typs.'/', $file )) {
						$sum += filesize ( $path . $file );
					}
				}
			}
			closedir ( $handle );
		}
		return $sum;
	}

	protected function DelFile($pfad){
		return @unlink($pfad);
	}

	protected function CheckFile($pfa){
		$dateihandler 	= 	fopen ($pfa,"r+");
		$datei 			=	fread ($dateihandler,filesize($pfa) );
		fclose($dateihandler);
		 
		return GFW_Validate::ValidateFile($datei,$pfa);

	}
	protected function UploadFile($file, $existfile = false){
		 
		$status = false;
		
        $this->checkDirs();
        
		if ($this->FileCountSize >= $this->FileCountSizeLimit or $this->FileSize >= $this->FileSizeLimit)
		{
			$this->error[] = MEDIA_ERROR_LIMIT;
			return false;
		}
		if(! $existfile){
			$file = $file['tmp_name'];
			$MAIN_ROOT_file = $file['tmp_name'];
			$filename = $file['name'];
			$filety = mime_content_type($file);
		}else{
			$tmp1 = explode('/',$file);
			$value =  count($tmp1);
			$filename = $tmp1[($value-1)];
			$MAIN_ROOT_file = $_SERVER['DOCUMENT_ROOT'].ConfigFile::Get('BASE_DIR').'/'.$file;
			$filety = mime_content_type($MAIN_ROOT_file);
		}
        
		foreach ( $this->filetyps as $typs ) {
			if (preg_match ( '#'.$typs.'#', $filety)) {
				if($typs == 'image/jpeg' or $typs == 'image/png' or $typs == 'image/gif' )
				if(!$existfile){
					$status = move_uploaded_file($MAIN_ROOT_file, $this->paths[1].$filename);
				}else{
					$status = copy($MAIN_ROOT_file, $this->paths[1].$filename);
				}
				if($typs == 'text/plain' or $typs == 'text/x-c'){
					if($this->CheckFile($file)){
						if(!$existfile){
							$status = move_uploaded_file($MAIN_ROOT_file, $this->paths[2].$filename);
						}else{
							$status = copy($MAIN_ROOT_file, $this->paths[2].$filename);
						}
						$this->ReplaceFiles($this->paths[2].$filename);
					}
				}
				if($typs == 'text/html'){
					if(!$existfile){
						$status =  move_uploaded_file($MAIN_ROOT_file, $this->paths[0].'index.html');
					}else{
						$status = copy($MAIN_ROOT_file,$this->paths[0].'index.html');
					}
					$this->ConvertTPL();
				}
				if($typs == 'application/zip'){
					$this->extractZip( $file, 'tmp/'.md5($filename));
				}
			}
		}
		if(!$status){
			$this->error[] = MEDIA_ERROR_FILE.$filename;
		}

		return $status;
	}
	public function GetError(){
		return $this->error;
	}
	protected function ConvertTPL() {
		if(!is_dir($this->obj->Settings['template_dir'].'user/'.$this->User_Id)){
			mkdir($this->obj->Settings['template_dir'].'user/'.$this->User_Id);
		}
		 
		$tpl = $this->obj->Settings['template_dir'].'user/'.$this->User_Id.'/index.tpl';
		$dateihandler 	= 	fopen ($this->paths[0].'index.html',"r+");
		$datei 			=	fread ($dateihandler,filesize($this->paths[0].'index.html') );
		fclose($dateihandler);
		 
		if (file_exists($tpl)){
			unlink($tpl);
		}
		 
		$datei = $this->ReplaceFiles($this->paths[0].'index.html',TRUE);
		 
		$dateihandler 	= 	fopen ($tpl,"w");

		if(fwrite($dateihandler,$datei) != false){
			fclose($dateihandler);
			return true;
		}else{
			fclose($dateihandler);
			return false;
		}
	}
	protected function ReplaceFiles($pfad,$output = false) {
		$dateihandler 	= 	fopen ($pfad,"r+");
		$datei 			=	fread ($dateihandler,filesize($_SERVER['DOCUMENT_ROOT'].ConfigFile::Get('BASE_DIR').'/'.$pfad) );
		fclose($dateihandler);
		 
		foreach ($this->inCl as $key => $inc){
			$datei =  preg_replace('!#'.$key.'#!',$inc,$datei);
		}

		if($output){
			return $datei;
		}else{
			if (file_exists($pfad)){
				unlink($pfad);
			}

			$dateihandler 	= 	fopen ($pfad,"w");
			if(fwrite($dateihandler,$datei) != false){
				fclose($dateihandler);
				return true;
			}else{
				fclose($dateihandler);
				return false;
			}
		}
	}
	protected function extractZip( $zipFile = '', $dirFromZip = '' ){
	    $zipDir = "";
		$count_files = 0;

		if(!file_exists($dirFromZip))
		{
			mkdir($dirFromZip);
		}

		$zip = zip_open($zipFile);
		if ($zip)
		{
			while ($zip_entry = zip_read($zip)){

				$completePath = $zipDir . dirname(zip_entry_name($zip_entry));
				$completeName = $zipDir . zip_entry_name($zip_entry);

				// Walk through path to create non existing directories
				// This won't apply to empty directories ! They are created further below
				 
				if(!file_exists($dirFromZip.'/'.$completePath))
				{
					$tmp = $dirFromZip.'/';
					foreach(explode('/',$completePath) AS $k)
					{
						$tmp .= $k.'/';
						if(!file_exists($tmp) )
						{
							mkdir($tmp, 0777);
						}
					}
				}

				if (zip_entry_open($zip, $zip_entry, "r"))
				{
					if( is_dir($dirFromZip .'/'.dirname(zip_entry_name($zip_entry))) )
					{
    					    if(!is_dir($dirFromZip.'/'.$completeName) && !preg_match ( '#\/$#',$completeName)){
        						if ($fd = fopen($dirFromZip.'/'.$completeName, 'w+'))
        						{
        							fwrite($fd, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
        							fclose($fd);
        							$count_files++;
        						}
    					    }else{
    							// We think this was an empty directory
    							if(!file_exists($completeName) )
    							{
    								mkdir($completeName, 0777);
    							}
        					}
    						zip_entry_close($zip_entry);
    
    						if(is_file($dirFromZip.'/'.$completeName)){
    							$this->UploadFile($dirFromZip.'/'.$completeName, true);
    						}
					    
					}
				}
				if($count_files >= $this->FileCountSizeLimit){
					break;
				}
			}
			zip_close($zip);
		}
		if(file_exists($dirFromZip))
		{
			$this->rec_rmdir($dirFromZip);
		}
		return true;
	}
	protected function rec_rmdir($path) {
		// schau' nach, ob das ueberhaupt ein Verzeichnis ist
		if (!is_dir ($path)) {
			return -1;
		}
		// oeffne das Verzeichnis
		$dir = @opendir ($path);

		// Fehler?
		if (!$dir) {
			return -2;
		}

		// gehe durch das Verzeichnis
		while (($entry = @readdir($dir)) !== false) {
			// wenn der Eintrag das aktuelle Verzeichnis oder das Elternverzeichnis
			// ist, ignoriere es
			if ($entry == '.' || $entry == '..') continue;
			// wenn der Eintrag ein Verzeichnis ist, dann
			if (is_dir ($path.'/'.$entry)) {
				// rufe mich selbst auf
				$res = $this->rec_rmdir ($path.'/'.$entry);
				// wenn ein Fehler aufgetreten ist
				if ($res == -1) { // dies duerfte gar nicht passieren
					@closedir ($dir); // Verzeichnis schliessen
					return -2; // normalen Fehler melden
				} else if ($res == -2) { // Fehler?
					@closedir ($dir); // Verzeichnis schliessen
					return -2; // Fehler weitergeben
				} else if ($res == -3) { // nicht unterstuetzer Dateityp?
					@closedir ($dir); // Verzeichnis schliessen
					return -3; // Fehler weitergeben
				} else if ($res != 0) { // das duerfe auch nicht passieren...
					@closedir ($dir); // Verzeichnis schliessen
					return -2; // Fehler zurueck
				}
			} else if (is_file ($path.'/'.$entry) || is_link ($path.'/'.$entry)) {
				// ansonsten loesche diese Datei / diesen Link
				$res = @unlink ($path.'/'.$entry);
				// Fehler?
				if (!$res) {
					@closedir ($dir); // Verzeichnis schliessen
					return -2; // melde ihn
				}
			} else {
				// ein nicht unterstuetzer Dateityp
				@closedir ($dir); // Verzeichnis schliessen
				return -3; // tut mir schrecklich leid...
			}
		}

		// schliesse nun das Verzeichnis
		@closedir ($dir);

		// versuche nun, das Verzeichnis zu loeschen
		$res = @rmdir ($path);

		// gab's einen Fehler?
		if (!$res) {
			return -2; // melde ihn
		}

		// alles ok
		return 0;
	}
	protected function formatBytes($b,$p = null) {
        $r["bytes"] = 0;
        $r["units"] = 0;
        
		$units = array("B","kB","MB","GB","TB","PB","EB","ZB","YB");
		$c=0;
		if(!$p && $p !== 0) {
			foreach($units as $k => $u) {
				if(($b / pow(1024,$k)) >= 1) {
					$r["bytes"] = $b / pow(1024,$k);
					$r["units"] = $u;
					$c++;
				}
			}
			return number_format($r["bytes"],2) . " " . $r["units"];
		} else {
			return number_format($b / pow(1024,$p)) . " " . $units[$p];
		}
	}
    protected function checkDirs(){
        try {
            foreach ($this->paths as $dirs){
                if(!is_dir($dirs)){
                    mkdir($dirs);
                }
            }
            return true;
        } catch (Exception $e) {
            return false;
        }    
    }
    
}
?>